package com.example.letgo.story;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.example.letgo.R;
import com.example.letgo.global.Constant;
import com.example.letgo.model.Story;
import com.example.letgo.trip.TripReleaseSuccess;
import com.google.gson.Gson;
import com.lljjcoder.citypickerview.widget.CityPicker;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import java.io.File;
import java.io.Serializable;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.common.LineConfig;
import cn.addapp.pickers.listeners.OnItemPickListener;
import cn.addapp.pickers.picker.SinglePicker;
import okhttp3.Call;
import okhttp3.Response;

public class StoryReleaseActivity extends AppCompatActivity {
    /***
     * 使用相册中的图片
     */
    public static final int SELECT_PIC_BY_PICK_PHOTO = 2;
    @BindView(R.id.type_choose)
    RelativeLayout typeChoose;
    @BindView(R.id.story_describe)
    EditText storyDescribe;
    @BindView(R.id.storyPlace)
    TextView storyPlace;
    @BindView(R.id.storyPlace_choose)
    RelativeLayout storyPlaceChoose;
    @BindView(R.id.endGroupTime_choose)
    RelativeLayout endGroupTimeChoose;
    @BindView(R.id.storyType)
    TextView storyType;
    /**
     * 获取到的图片路径
     */
    private String picPath;
    /**
     * 获取到的图片路径
     */
    private String picPath1;
    private Uri photoUri;
    @BindView(R.id.story_return_person)
    ImageView storyReturnPerson;
    @BindView(R.id.shear)
    TextView shear;
    @BindView(R.id.text1)
    EditText text1;
    @BindView(R.id.Img1)
    ImageView Img1;
    @BindView(R.id.text2)
    EditText text2;
    @BindView(R.id.Img2)
    ImageView Img2;
    @BindView(R.id.text3)
    EditText text3;
    @BindView(R.id.activity_story_release)
    LinearLayout activityStoryRelease;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_story_release);
        ButterKnife.bind(this);
    }


    @OnClick({R.id.story_return_person, R.id.shear, R.id.Img1, R.id.Img2, R.id.storyPlace_choose})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.story_return_person:
                finish();
                break;
            case R.id.shear:
                if (storyType.getText()!=null&&storyPlace.getText() != null && storyDescribe.getText() != null && text1.getText() != null && text2.getText() != null && text3.getText() != null) {
                    int userId = Constant.id;
                    File file = new File(picPath);
                    File file1 = new File(picPath1);
                    String startTime = systemTime();
                    //将story的数据装进实体并传送到下一个activity
                    final Story story = new Story();
                    story.setStoryDescribe(storyDescribe.getText().toString());
                    story.setStoryImage(picPath);
                    story.setStoryImg1(picPath);
                    story.setStoryImg2(picPath1);
                    story.setStoryOverPlace(storyPlace.getText().toString());
                    story.setStoryText1(text1.getText().toString());
                    story.setStoryText2(text2.getText().toString());
                    story.setStoryText3(text3.getText().toString());
                    story.setStoryTime(startTime);
                    story.setStoryUserId(userId);
                    story.setStoryType(storyType.getText().toString());
                    OkGo.post("http://119.29.113.114:8080/gogogo/story/add")
                            .params("storyUserId", userId)
                            .params("storyImageFile", file)
                            .params("storyDescribe", storyDescribe.getText().toString())
                            .params("storyOverPlace", storyPlace.getText().toString())
                            .params("storyTime", startTime)
                            .params("storyText1", text1.getText().toString())
                            .params("storyText2", text2.getText().toString())
                            .params("storyText3", text3.getText().toString())
                            .params("storyImg1File", file)
                            .params("storyImg2File", file1)
                            .params("storyType",storyType.getText().toString())
                            .execute(new StringCallback() {
                                @Override
                                public void onSuccess(String s, Call call, Response response) {
                                    Intent intent = new Intent(StoryReleaseActivity.this, StoryReleaseSuccess.class);
                                    intent.putExtra("story", new Gson().toJson(story));
                                    startActivity(intent);
                                    finish();
                                }

                                @Override
                                public void onError(Call call, Response response, Exception e) {
                                    super.onError(call, response, e);
                                    Log.e("Tag,errro:", String.valueOf(e));
                                    Toast.makeText(StoryReleaseActivity.this, "服务器异常!", Toast.LENGTH_SHORT).show();
                                }
                            });
                } else {
                    Toast.makeText(this, "请完善内容！", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.Img1:
                Intent intentI = new Intent();
                intentI.setType("image/*");
                intentI.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intentI, SELECT_PIC_BY_PICK_PHOTO);
                break;
            case R.id.Img2:
                Intent intentI2 = new Intent();
                intentI2.setType("image/*");
                intentI2.setAction(Intent.ACTION_GET_CONTENT);
                startActivityForResult(intentI2, SELECT_PIC_BY_PICK_PHOTO);

                break;
            case R.id.storyPlace_choose:
                CityPicker cityPicker = new CityPicker.Builder(StoryReleaseActivity.this)
                        .textSize(14)
                        .title("地址选择")
                        .titleBackgroundColor("#FFFFFF")
                        .confirTextColor("#696969")
                        .cancelTextColor("#696969")
                        .province("江苏省")
                        .city("常州市")
                        .district("天宁区")
                        .textColor(Color.parseColor("#000000"))
                        .provinceCyclic(true)
                        .cityCyclic(false)
                        .districtCyclic(false)
                        .visibleItemsCount(7)
                        .itemPadding(10)
                        .onlyShowProvinceAndCity(false)
                        .build();
                cityPicker.show();
                //监听方法，获取选择结果
                cityPicker.setOnCityItemClickListener(new CityPicker.OnCityItemClickListener() {
                    @Override
                    public void onSelected(String... citySelected) {
                        //省份
                        String province = citySelected[0];
                        //城市
                        String city = citySelected[1];
                        //区县（如果设定了两级联动，那么该项返回空）
                        String district = citySelected[2];
                        //邮编
                        String code = citySelected[3];
                        //为TextView赋值
                        storyPlace.setText(province.trim() + "-" + city.trim() + "-" + district.trim());
                    }
                });
                break;
        }
    }

    @OnClick(R.id.type_choose)
    public void onViewClicked() {
        boolean isChinese = Locale.getDefault().getDisplayLanguage().contains("中文");
        SinglePicker<String> pickerP = new SinglePicker<>(this,
                isChinese ? new String[]{
                        "游记", "攻略", "美食"
                } : new String[]{
                        "游记", "攻略", "美食"
                });
        pickerP.setCanLoop(false);//不禁用循环
        pickerP.setTopBackgroundColor(0xFFEEEEEE);
        pickerP.setTopHeight(50);
        pickerP.setTopLineColor(0xFF33B5E5);
        pickerP.setTopLineHeight(1);
        pickerP.setTitleText(isChinese ? "请选择" : "Please pick");
        pickerP.setTitleTextColor(0xFF999999);
        pickerP.setTitleTextSize(12);
        pickerP.setCancelTextColor(0xFF33B5E5);
        pickerP.setCancelTextSize(13);
        pickerP.setSubmitTextColor(0xFF33B5E5);
        pickerP.setSubmitTextSize(13);
        pickerP.setSelectedTextColor(0xFFEE0000);
        pickerP.setUnSelectedTextColor(0xFF999999);
        pickerP.setWheelModeEnable(true);
        LineConfig configP = new LineConfig();
        configP.setColor(Color.BLUE);//线颜色
        configP.setAlpha(120);//线透明度
        pickerP.setLineConfig(configP);
        pickerP.setItemWidth(200);
        pickerP.setBackgroundColor(0xFFE1E1E1);
        //picker.setSelectedItem(isChinese ? "处女座" : "Virgo");
        pickerP.setSelectedIndex(7);
        pickerP.setOnItemPickListener(new OnItemPickListener<String>() {
            @Override
            public void onItemPicked(int index, String item) {
                storyType.setText(item);
            }
        });
        pickerP.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (resultCode == Activity.RESULT_OK) {
            if (Img1.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.add_image).getConstantState() && Img2.getDrawable().getCurrent().getConstantState() == getResources().getDrawable(R.mipmap.add_image).getConstantState()) {
                doPhoto(requestCode, data);
            } else {
                doPhoto1(requestCode, data);
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 选择图片后，获取图片的路径
     *
     * @param requestCode
     * @param data
     */
    private void doPhoto(int requestCode, Intent data) {
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) //从相册取图片，有些手机有异常情况，请注意
        {
            if (data == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
            photoUri = data.getData();
            if (photoUri == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.e(">>>>>>>", "imagePath = " + picPath);
        if (picPath != null && (picPath.endsWith(".png") || picPath.endsWith(".PNG") || picPath.endsWith(".jpg") || picPath.endsWith(".JPG"))) {
            Img1.setImageURI(Uri.fromFile(new File(picPath)));
        } else {
            Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
        }

    }

    private void doPhoto1(int requestCode, Intent data) {
        if (requestCode == SELECT_PIC_BY_PICK_PHOTO) //从相册取图片，有些手机有异常情况，请注意
        {
            if (data == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
            photoUri = data.getData();
            if (photoUri == null) {
                Toast.makeText(this, "选择图片文件出错", Toast.LENGTH_LONG).show();
            }
        }
        String[] pojo = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(photoUri, pojo, null, null, null);
        if (cursor != null) {
            int columnIndex = cursor.getColumnIndexOrThrow(pojo[0]);
            cursor.moveToFirst();
            picPath1 = cursor.getString(columnIndex);
            cursor.close();
        }
        Log.e(">>>>>>>", "imagePath = " + picPath);
        Log.e(">>>>>>>", "imagePath1 = " + picPath1);
        if (picPath1 != null && (picPath1.endsWith(".png") || picPath1.endsWith(".PNG") || picPath1.endsWith(".jpg") || picPath1.endsWith(".JPG"))) {
            Img2.setImageURI(Uri.fromFile(new File(picPath1)));
        } else {
            Toast.makeText(this, "选择图片文件不正确", Toast.LENGTH_LONG).show();
        }

    }

    public String systemTime() {
        Time t = new Time(); // or Time t=new Time("GMT+8"); 加上Time Zone资料。
        t.setToNow(); // 取得系统时间。
        int year = t.year;
        int month = t.month;
        int day = t.monthDay;
        int hour = t.hour; // 0-23
        int minute = t.minute;
        String startTime = year + "-" + month + "-" + day + "-" + hour + ":" + minute;
        return startTime;
    }

}
